import {
	getAlarmPage,
	insertAlarm,
	updateAlarm,
	delAlarm,
	sendMsg,
	updateAlarmStatus,
} from "@/api/robotTask";
import { getAllBrandsPage } from "@/api/brand";
import { getProjLists } from "@/api/order";
import { getDataByCode, checkUserToken } from "@/api/user";
import { curentTime, curentDate } from "@/filters/index";
import waves from "@/directive/waves"; // waves directive
import Pagination from "@/components/Pagination"; //  分页器
import pdf from "@/components/pdf"; //  pdf预览
import checkPermission from "@/utils/permission"; // 权限判断函数
import { paramsDataDeal } from "@/utils/index";
// 导入模块
import vueJsonEditor from "vue-json-editor";

export default {
	name: "robotTask",
	components: { Pagination, vueJsonEditor, pdf },
	directives: { waves },
	filters: {
		formate(date) {
			return curentTime(date);
		},
	},
	data() {
		return {
			pickerOptions: {
				disabledDate: (time) => {
					return time.getTime() < Date.now() - 24 * 60 * 60 * 1000;
				},
			},
			statusArr: [
				{
					name: "未开始",
					code: "NOT_START",
				},
				{
					name: "进行中",
					code: "START",
				},
				{
					name: "已结束",
					code: "END",
				},
			],
			timeTypeArr:[
				{
					name: "通知截止日期",
					code: "alarm_endtime"
				},
				{
					name: "创建时间",
					code: "created_at"
				},
				{
					name: "修改时间",
					code: "updated_at"
				}
			],
			// 项目数据
			pageList: [],
			// 项目总数
			total: 0,
			// 加载
			listLoading: true,
			// 查询参数
			listQuery: {
				pageNum: 1,
				pageSize: 10,
				filterDateType: null,
				filterDate: null,
				alarmStyle: null,
				alarmStatus: null,
				searchKey: null
			},
			searchKey: "",
			// 表单控制
			dialogFormVisible: false,
			// 表单标题
			title: "",
			// 表单参数
			form: {
				id: "",
				alarmName: "",
				alarmContent: "",
				alarmType: "",
				alarmUseridArr: [],
				alarmEndtime: "",
				alarmTime: "",
				alarmUserid: "",
				alarmInner: "",
				brandId: null,
				brandName: null,
				projectId: null,
				projectName: null,
				alarmStyle: null,
			},
			orderIDs: "",
			// 表单检验
			rules: {
				alarmName: [
					{ required: true, message: "请输入通知名称", trigger: "change" },
				],
				alarmType: [
					{ required: true, message: "请选择通知类型", trigger: "change" },
				],
				alarmEndtime: [
					{ required: true, message: "请选择通知时间", trigger: "change" },
				],
				alarmTime: [
					{ required: true, message: "请选择提前通知天数", trigger: "change" },
				],
				alarmUseridArr: [
					{ required: true, message: "请选择负责人", trigger: "change" },
				],
				alarmInner: [
					{ required: true, message: "请输入通知配置内容", trigger: "change" },
				],
			},
			// 通知方式
			robotAlarmTypeLists: [],
			userLists: [],
			currTagUserId: "", //  当前用户的unionId
			// json是否验证通过
			hasJsonFlag: true,
			brandsLists: [], //	品牌列表
			projectLists: [], //	项目列表
			alarmStyleLists: [],
			isDetails: false,
			pdfurl: "https://morefun-active.oss-cn-beijing.aliyuncs.com/morefun_oa/%E9%80%9A%E7%94%A8%E4%BB%BB%E5%8A%A1%E5%91%8A%E8%AD%A6.pdf",
			pdfhref: "https://morefun.yuque.com/kd0dsy/pyy99r/oac8sixkmadtda8n"
		};
	},
	async created() {
		//	获取项目列表
		this.getProjLists();
		//	获取品牌列表
		this.getAllBrandsPage();

		await this.getPageList();

		// 获取配置数据
		getDataByCode({ code: "RobotAlarm,OnJobUser,AlarmStyle" }).then((res) => {
			this.robotAlarmTypeLists = res.data.RobotAlarm || null;
			this.userLists = res.data.OnJobUser || null;
			this.alarmStyleLists = res.data.AlarmStyle || null;
		});
	},
	mounted() {},
	methods: {
		checkPermission,
		//	提前多少天通知修改
		handleChange(value) {
			this.form.alarmTime = value;
		},
		//	获取项目列表
		async getProjLists() {
			const projects = await getProjLists();
			if (projects.success) {
				this.projectLists = projects.data;
			}
		},
		//	获取品牌信息
		async getAllBrandsPage() {
			const brands = await getAllBrandsPage();
			if (brands.success) {
				this.brandsLists = brands.data;
			}
		},
		//	项目选中
		projectIdSel(e) {
			const _item = this.projectLists.filter((item) => {
				return item.project_name == e;
			});
			this.form.projectName = e || null;
      this.form.projectId = e && _item[0]  ? _item[0].id : null;
		},
		//	品牌选中
		brandIdSel(e) {
			const _item = this.brandsLists.filter((item) => {
				return item.brand_name == e;
			});
			this.form.brandName = e || null;
      this.form.brandId = e && _item[0] ? _item[0].id : null;
			if(!_item[0] || !_item[0].alarm_config) return console.log("######  当前品牌数据暂未配置钉钉通知信息  ######")
      if (this.form.alarmInner) {
        this.$confirm('通知配置已经有内容，是否覆盖?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
					this.form.alarmType = 'GroupRobot';
          this.form.alarmInner = JSON.parse(_item[0].alarm_config);
					//  解决this.$confirm出现时 select选择展开问题
          this.$refs.selectBrandName1.blur();
        }).catch(() => {
					//  解决this.$confirm出现时 select选择展开问题
          this.$refs.selectBrandName1.blur();
        });
      }else{
        this.form.alarmInner = JSON.parse(_item[0].alarm_config);
      }
		},
		// json编辑器回调方法
		onJsonSave(value) {
			this.form.alarmInner = value;
			this.hasJsonFlag = true;
		},
		onError(value) {
			this.hasJsonFlag = false;
		},
		// 通知类型选择回调方法
		async alarmTypeSel(e) {
			let res = await getDataByCode({ code: e });

			if (this.form.alarmInner) {
        this.$confirm('通知配置已经有内容，是否覆盖?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.form.alarmInner = res.success ? res.data[e] : {};
					//  解决this.$confirm出现时 select选择展开问题
          this.$refs.selectAlarmType1.blur();
        }).catch(() => {
          //  解决this.$confirm出现时 select选择展开问题
          this.$refs.selectAlarmType1.blur();     
        });
      }else{
        this.form.alarmInner = res.success ? res.data[e] : {};
      }
		},

		/**
		 * 筛选过滤查询
		 * @param {*} e 
		 */
		async handleFilter() {
			this.listQuery.pageNum = 1;
			await this.getPageList();
		},
		// 查询项目数据
		async getPageList() {
			try {
				//	处理请求参数
				const _obj = JSON.parse(JSON.stringify(this.listQuery));

				if(!_obj.filterDateType || !_obj.filterDate){
					delete _obj.filterDateType;
					delete _obj.filterDate;
				}

				const _params = await paramsDataDeal(_obj);
				const res = await getAlarmPage(_params);
				this.currTagUserId = res.data.id;
				this.total = res.data.total;
				this.pageList = res.data.lists;
				this.listLoading = false;
			} catch (error) {
				console.log(error);
			}
		},

		// 提交表单信息
		async submitForm(formName) {
			// 负责人
			if (!this.form.alarmUseridArr || !this.form.alarmUseridArr.length) {
				return this.$message({
					message: "负责人不能为空！",
					type: "error",
				});
			}

			//  筛选需要通知的用户数据
			let alarmUserid = [];
			for (let i = 0; i < this.userLists.length; i++) {
				const el = this.userLists[i];
				for (let k = 0; k < this.form.alarmUseridArr.length; k++) {
					const _unionid = this.form.alarmUseridArr[k];
					if (el.unionid == _unionid) {
						alarmUserid.push({
							userid: el.userid,
							unionid: el.unionid,
							name: el.name,
						});
					}
				}
			}
			this.form.alarmUserid = alarmUserid;
			// 表单验证
			this.$refs[formName].validate(async (valid) => {
				if (valid) {
					if (typeof this.form.alarmEndtime == "object") {
						this.form.alarmEndtime = curentDate(this.form.alarmEndtime);
					}

					let _obj = JSON.parse(JSON.stringify(this.form));
					delete _obj.alarmUseridArr;

					const _params = await paramsDataDeal(_obj);

					if (this.form.id) {
						console.log("######  修改数据", _params);
						updateAlarm(_params).then((res) => {
							this.$message({
								message: "修改成功",
								type: "success",
							});
							this.getPageList();
							this.dialogFormVisible = false;
						});
					} else {
						console.log("######  新增数据", _params);
						insertAlarm(_params).then((res) => {
							this.$message({
								message: "新增成功",
								type: "success",
							});
							this.getPageList();
							this.dialogFormVisible = false;
						});
					}
				} else {
					return false;
				}
			});
		},

		// 取消
		resetForm(formName) {
			this.dialogFormVisible = false;
			this.isDetails = false;
			// this.form = {
			// 	id: "",
			// 	alarmName: "",
			// 	alarmContent: "",
			// 	alarmType: "",
			// 	alarmUseridArr: [],
			// 	alarmEndtime: "",
			// 	alarmTime: "",
			// 	alarmUserid: "",
			// 	alarmInner: "",
			// 	brandId: null,
			// 	brandName: null,
			// 	projectId: null,
			// 	projectName: null,
			// 	alarmStyle: null,
			// }
		},
		// 新增通知任务
		handleAdd() {
			checkUserToken().then((res) => {
				if (res.data) {
					this.title = "新增通知任务";
					this.isDetails = false;
					this.$delete(this.form, "id");
					this.form.alarmUseridArr = [this.currTagUserId];
					this.form.alarmEndtime = "";
					this.form.alarmTime = "";
					this.form.alarmName = "";
					this.form.alarmContent = null;
					this.form.alarmType = "";
					this.form.alarmInner = null;
					this.form.brandId = null;
					this.form.brandName = null;
					this.form.projectId = null;
					this.form.projectName = null;
					this.form.alarmStyle = null;
					this.$nextTick(() => {
						this.$refs["form"].resetFields();
					});
					this.dialogFormVisible = true;
				}
			});
		},
		//	查看详情
		handleDataDetails(row){
			this.title = "查看通知任务";
			this.dialogFormVisible = true;
			this.isDetails = true;
			this.$nextTick(() => {
				if(this.$refs['form']){
					this.$refs['form'].clearValidate();
				}
				this.form.id = row.id;
				this.form.alarmName = row.alarm_name;
				this.form.alarmContent = row.alarm_content;
				this.form.alarmType = row.alarm_type;
				this.form.alarmEndtime = new Date(row.alarm_endtime);
				this.form.alarmTime = row.alarm_time;
				this.form.alarmInner = JSON.parse(row.alarm_inner);
				this.form.brandId = row.brand_id || null;
				this.form.brandName = row.brand_name || null;
				this.form.projectId = row.project_id || null;
				this.form.projectName = row.project_name || null;
				this.form.alarmStyle = row.alarm_style || null;
				if (row.alarm_userid) {
					const _ids = row.alarm_userid.split(",");
					this.form.alarmUseridArr = [];
					_ids.forEach((el) => {
						this.userLists.forEach((item) => {
							if (el == item.userid) {
								this.form.alarmUseridArr.push(item.unionid);
							}
						});
					});
				}
			});
		},
		// 启动/结束任务
		async handleDetails(row) {
			let _msg = "";
			let _alarmStatus = "";
			if (row.alarm_status == "NOT_START" || row.alarm_status == "END") {
				_alarmStatus = "START";
				_msg = "启动";
			} else if (row.alarm_status == "START") {
				_alarmStatus = "END";
				_msg = "结束";
			}

			if (_msg && _alarmStatus) {
				//  发送通知验证消息
				const res = await sendMsg({ id: row.id, msg: _msg });
				if (res && res.success) {
					this.$message({
						message: _msg + "通知已成功发送钉钉，请查看",
						type: "success",
					});
					// 更新通知任务状态
					await updateAlarmStatus({ id: row.id, alarmStatus: _alarmStatus });
					// 重新获取列表
					this.getPageList();
				} else {
					this.$message({
						message: _msg + "通知已成功发送钉钉，请查看",
						type: "fail",
					});
				}
			}
		},
		// 修改
		handleModify(row) {
			if (row.alarm_status === "START")
				return this.$message({
					type: "info",
					message: "任务状态为“进行中”，请结束任务再执行修改操作",
				});
			this.title = "修改通知任务";
			this.dialogFormVisible = true;
			this.isDetails = false;
			this.$nextTick(() => {
				if(this.$refs['form']){
					this.$refs['form'].clearValidate();
				}
				this.form.id = row.id;
				this.form.alarmName = row.alarm_name;
				this.form.alarmContent = row.alarm_content;
				this.form.alarmType = row.alarm_type;
				this.form.alarmEndtime = new Date(row.alarm_endtime);
				this.form.alarmTime = row.alarm_time;
				this.form.alarmInner = JSON.parse(row.alarm_inner);
				this.form.brandId = row.brand_id || null;
				this.form.brandName = row.brand_name || null;
				this.form.projectId = row.project_id || null;
				this.form.projectName = row.project_name || null;
				this.form.alarmStyle = row.alarm_style || null;
				if (row.alarm_userid) {
					const _ids = row.alarm_userid.split(",");
					this.form.alarmUseridArr = [];
					_ids.forEach((el) => {
						this.userLists.forEach((item) => {
							if (el == item.userid) {
								this.form.alarmUseridArr.push(item.unionid);
							}
						});
					});
				}
			});
		},

		// 删除
		handleDelete(row) {
			if (row.alarm_status === "START")
				return this.$message({
					type: "info",
					message: "任务状态为“进行中”，请结束任务再执行删除操作",
				});
			this.$confirm("此操作将删除该任务通知, 是否继续?", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			})
				.then(() => {
					delAlarm({ id: row.id }).then((res) => {
						this.$message({
							message: "删除成功",
							type: "success",
						});
						this.getPageList();
					});
				})
				.catch(() => {
					this.$message({
						type: "info",
						message: "已取消删除",
					});
				});
		},

		// 输入字数限制
		changeValue(attr, byte) {
			let value = this.form[attr]; //校验的字段
			// 中文、中文标点、全角字符按1长度，英文、英文符号、数字按0.5长度计算
			let cnReg = /([\u4e00-\u9fa5]|[\u3000-\u303F]|[\uFF00-\uFF60])/;
			let maxLimitStr = byte; //25个汉字
			let pass = true;
			let substringStr = "";
			let length = 0;
			let strArr = value.split("");
			strArr.map((str) => {
				if (pass) {
					if (cnReg.test(str)) {
						//中文
						length++;
					} else {
						//英文
						length += 0.5;
					}
					//大于最大限制的时候
					if (length > maxLimitStr) {
						pass = false;
						//将校验的字符截取返回
						this.form[attr] = substringStr;
					} else {
						substringStr += str;
					}
				}
			});
			return pass;
		},
	},
};